package com.example.sentinel.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class CustomBlockHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response, BlockException e) throws Exception {
        String msg = "未知错误";
        if (e instanceof FlowException) {
            msg = "被限流了";
        } else if (e instanceof DegradeException) {
            msg = "被熔断降级了";
        } else if (e instanceof ParamFlowException) {
            msg = "热点参数限流";
        } else if (e instanceof SystemBlockException) {
            msg = "系统自适应限流（负载/...不满足要求）";
        } else if (e instanceof AuthorityException) {
            msg = "黑名单控制";
        }
        log.error("Sentinel：" + msg);
        response.setHeader("Content-Type", "text/html;charset=utf-8");
        response.getWriter().println(msg);
    }
}
